import logging
import pytest


def pytest_collection_modifyitems(items):
    """
    hook:处理中文的unicode显示问题
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")


def pytest_addoption(parser):
    """
    hook：添加命令行参数
    """
    my_group = parser.getgroup("xiaofo")
    my_group.addoption("--fo",
                       default='debug',
                       dest='fo',
                       help='set your logger level')


@pytest.fixture(scope='session')
def logger_on_option(request):
    """
    fixture:获取命令行参数，设定logger
    """
    cmd = request.config.getoption("--fo")
    if cmd == 'warn':
        lvl = logging.WARNING
    elif cmd == 'info':
        lvl = logging.INFO
    else:
        lvl = logging.DEBUG

    logging.basicConfig(level=logging.INFO,
                        # 日志格式
                        # 时间、代码所在文件名、代码行号、日志级别名字、日志信息
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        # 打印日志的时间
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        # 日志文件存放的目录（目录必须存在）及日志文件名
                        filename='./logs/run.log',
                        # 打开日志文件的方式
                        filemode='w'
                        )
    logger = logging.getLogger(__name__)
    return lvl, logger
